package cn.xiaoliu.hrm.filter;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SmsCodeFilter extends OncePerRequestFilter{
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取当前请求的uri
        String uri = httpServletRequest.getRequestURI();
        //判断uri是否是验证码登录
        if ("/smslogin".equals(uri)){
            String phone = httpServletRequest.getParameter("phone");
            String code = httpServletRequest.getParameter("code");
            //获取当前请求的会话，拿到会话中的验证码
            String scode = (String) httpServletRequest.getSession().getAttribute("smscode::" + phone);
            //用户可能没有传参数，或者传的参数为空，比对成功放行，比对失败抛错
            if (code != null && !code.equalsIgnoreCase(scode)){
                throw new RuntimeException("验证码有误");
            }
        }
        //其他请求放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
